<template>
  <div class="tempeleteFrom" ref="extendBaseForm">
    <!-- <a-tabs v-model:activeKey="activeKey" type="card" class="tab_card" @change="tabChange">
      <a-tab-pane key="1" tab=""></a-tab-pane>
      <a-tab-pane key="2" tab="移动端模版设置"></a-tab-pane>
    </a-tabs> -->
    <div class="tab-pane">
      <span>
        PC端模版设置
      </span>
      <span>
        移动端模版设置
      </span>
    </div>
    <div class="scrollContent">
      <div class="scrollContent_form">
        <div class="form_item" @click="activeKey = 1">
          <newBaseForm :form="formState.PC" :noWatermark="1" ref="getbaseForm" @onChangeSelect="onChangeSelect">
          </newBaseForm>
        </div>
        <div class="form_item" @click="activeKey = 2">
          <newBaseForm :form="formState.Mobile" :noWatermark="1" ref="getbaseForm" @click="activeKey = 2"
            @onChangeSelect="onChangeSelect">
          </newBaseForm>
        </div>

      </div>

      <div class="globalContentModels">
        <a-checkbox-group v-model:value="globalContentModelSelect" name="checkboxgroup" :options="globalContentModels.map((item: any) => ({
          'label': item.modelName, value: item.modelId
        }))" />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, nextTick, onMounted, computed } from "vue";
import { dataSourceType } from "@/type.d";
import { comSelectCfg, tplForm } from "./tplFormConfig";
import { cloneDeep } from "lodash";
import newBaseForm from "@/components/form/newBaseForm.vue";

import { useRouter } from "vue-router";
import request from "@/api/index";
// props
const props = defineProps({
  tempeleteInfo: {
    type: Object,
    default: {},
  },
  siteId: {
    type: Number || undefined,
    default: 1,
  },
});
// data
const activeKey = ref<number | string>('1');
const formState = ref<dataSourceType>(cloneDeep(tplForm));
const mobileTplSetup = reactive<dataSourceType>({
  "channelModels": [] as dataSourceType[],
  "contentModels": [] as dataSourceType[],
  "homeTpl": "",
  "templateDir": ""
});
const pcTplSetup = reactive<dataSourceType>({
  "channelModels": [] as dataSourceType[],
  "contentModels": [] as dataSourceType[],
  "homeTpl": "",
  "templateDir": ""
})
const tempeleteInfo = ref<any>();
const getbaseForm = ref();
//全局内容模型
const globalContentModels = ref<dataSourceType[]>([]);
const globalContentModelSelect = ref<(string | number)[]>([]);
//模型相关
const originTpl = ref<any>('');
const modelIdList = ref<any[]>([]);
// saveData
let saveTplData = ref<any>({});
//watch
watch(
  () => tempeleteInfo.value,
  (newVal, oldVal) => {
    if (!newVal) {
      formState.value = cloneDeep(tplForm);
      return;
    }
    if (JSON.stringify(newVal)) {
      setModelIdList();
      setChannelContent();
    }
  }, { deep: true }
);
watch(() => formState.value, (newVal, oldVal) => {
  //pc
  pcTplSetup.homeTpl = newVal.PC.homeTpl;
  pcTplSetup.templateDir = newVal.PC.templateDir;
  //mobile
  mobileTplSetup.homeTpl = newVal.Mobile.homeTpl;
  mobileTplSetup.templateDir = newVal.Mobile.templateDir;
}, { deep: true })
//computed
saveTplData = computed(() => {
  return {
    mobileTplSetup,
    pcTplSetup,
    globalContentModels: globalContentModelSelect.value
  }
})
//methods
// 获取站点模板信息
const getSiteDetail_tempeleteInfo = async () => {
  let data: dataSourceType = {
    siteId: props.siteId,
  };
  request
    .fetchSiteManageGetSiteDetail_tempeleteInfo(data)
    .then((res: dataSourceType) => {
      if (res.code = '00000 00000') {
        tempeleteInfo.value = [];
        tempeleteInfo.value = res;
        getTplfolderList();
      }

    });
};
// 获取模板方案数据
const getTplfolderList = async () => {
  const telData = await request.getTplfolderList({});
  nextTick(() => {
    let options: dataSourceType[] = telData.map((item: dataSourceType) => { return { label: item, value: item } })
    formState.value.PC.formState[0].children[0].options = options;
    formState.value.Mobile.formState[0].children[0].options = options;
  })
}
// tab发生改变时
const tabChange = () => {
  getAllOptions();
  getTplfolderList();
}
// 模板选项改变时
const onChangeSelect = async (index1: any, index2: any, dataItem: any) => {

  nextTick(() => {

    if (index1 == 0) { // 意味着是模板选择发生改变
      console.log(dataItem.value, 'dataItem.value')
      activeKey.value == '1' ? (pcTplSetup.templateDir = cloneDeep(formState.value.PC.templateDir)
        && (formState.value.PC.formState[0].children[0].value = formState.value.PC.templateDir)) :
        (mobileTplSetup.templateDir = cloneDeep(formState.value.Mobile.templateDir) &&
          (formState.value.Mobile.formState[0].children[0].value = formState.value.Mobile.templateDir));
      if (!dataItem.value) {
        originTpl.value = cloneDeep(formState.value);
      }
      if (dataItem.value) {
        if (dataItem.value == originTpl.value.PC.templateDir && activeKey.value == '1') {
          formState.value.PC = cloneDeep(originTpl.value.PC);
        }
        if (dataItem.value == originTpl.value.Mobile.templateDir && activeKey.value == '2') {
          formState.value.Mobile = cloneDeep(originTpl.value.Mobile);
        }
        if ((activeKey.value == '1' && dataItem.value != originTpl.value.PC.templateDir) || (activeKey.value == '2' && dataItem.value != originTpl.value.Mobile.templateDir)) {
          console.log(activeKey.value, 'activeKey.value');
          if (activeKey.value == '1') { // 选择了非默认模板要把已选择置空
            for (let i in formState.value['PC']) {
              if (i != 'templateDir' && i != 'formState') {
                formState.value['PC'][i] = '';
              }
            }
          } else {
            for (let i in formState.value['Mobile']) {
              if (i != 'templateDir' && i != 'formState') {
                formState.value['Mobile'][i] = '';
              }
            }
          }
        }
      }
      getAllOptions();
      getTplfolderList();
    } else if (index1 == 1) { // 首页选择发生改变
      if (activeKey.value == '1') {
        pcTplSetup.homeTpl = formState.value.PC.homeTpl;
      } else {
        mobileTplSetup.homeTpl = formState.value.Mobile.homeTpl
        formState.value.Mobile.homeTpl;
      }
    } else if (index1 == 2 || index1 == 3) { // 说明改变的是channel 或者内容
      console.log(pcTplSetup['channelModels'], pcTplSetup['contentModels'], "pcTplSetup['channelModels'], pcTplSetup['contentModels'],")
      let type: string = index1 == 2 ? 'channelModels' : 'contentModels';
      let arr = activeKey.value == '1' ? cloneDeep(pcTplSetup[type]) : cloneDeep(mobileTplSetup[type]);
      let findIndex: any = ''
      arr.forEach((item: dataSourceType, index: number) => {
        if (item.modelId == dataItem.param) {
          findIndex = index;
          item.value = activeKey.value == '1' ? formState.value.PC[dataItem.param] : formState.value.Mobile[dataItem.param];
        };
      })
      let obj: dataSourceType = {
        modelId: dataItem.param,
        tplPath: activeKey.value == '1' ? formState.value.PC[dataItem.param] : formState.value.Mobile[dataItem.param],
      }
      if (findIndex !== '') {
        arr[findIndex] = obj;
      } else {
        arr.push(obj);
      }
      activeKey.value == '1' ? pcTplSetup[type] = cloneDeep(arr) : mobileTplSetup[type] = cloneDeep(arr);
      console.log(pcTplSetup, 'pcTplSetup',)
    }

  })


}
//获取所有模板选项
const getAllOptions = async () => {
  let params = {
    "modelIdList": modelIdList.value,
    "templateScenarios": activeKey.value == '1' ? formState.value.PC.templateDir : formState.value.Mobile.templateDir,
    "siteId": props.siteId,
  }
  const telData = await request.getSiteTplList(params);
  nextTick(() => {
    for (let i in telData.data) {
      [1, 2, 3].forEach((num: number) => {
        formState.value[activeKey.value == '1' ? 'PC' : 'Mobile'].formState[num].children.forEach((cItem: dataSourceType) => {
          if (cItem.param == i) {
            cItem.options = telData.data[i].map((opItem: dataSourceType) => { return { label: opItem, value: opItem } })
          }
        })
      })
    }
    formState.value[activeKey.value == '1' ? 'PC' : 'Mobile'].formState[1].children[0].options = telData.data.homeTpl.map((opItem: dataSourceType) => { return { label: opItem, value: opItem } })
  });
}
// 获取所有的模型
const setModelIdList = () => {
  let newVal = tempeleteInfo.value;
  globalContentModels.value = newVal.globalContentModels;
  globalContentModelSelect.value = globalContentModels.value.reduce((arr: (string | number)[], item: any) => {
    if (item.isSelect) {
      arr.push(item.modelId);
    }
    return arr
  }, []);
  modelIdList.value = ((newVal.pcTplSetup.channelModels).concat(newVal.pcTplSetup.contentModels)).reduce((arr: (string | number)[], item: any) => {
    arr.push(item.modelId);
    return arr
  }, []);
  formState.value.PC.templateDir = newVal['pcTplSetup'].templateDir || undefined;
  formState.value.PC.homeTpl = newVal['pcTplSetup'].homeTpl || undefined;
  formState.value.Mobile.templateDir = newVal['mobileTplSetup'].templateDir || undefined;
  formState.value.Mobile.homeTpl = newVal['mobileTplSetup'].homeTpl || undefined;

  // 初始化已选择的模型模板
  mobileTplSetup.channelModels = newVal.mobileTplSetup.channelModels.filter((item: dataSourceType) => item.tplPath);
  mobileTplSetup.contentModels = newVal.mobileTplSetup.contentModels.filter((item: dataSourceType) => item.tplPath);
  pcTplSetup.channelModels = newVal.pcTplSetup.channelModels.filter((item: dataSourceType) => item.tplPath);
  pcTplSetup.contentModels = newVal.pcTplSetup.contentModels.filter((item: dataSourceType) => item.tplPath);

}
//配置栏目和内容的模型对应模板
const setChannelContent = () => {
  let data = tempeleteInfo.value;
  let Lists: any[] = []
  formState.value.PC.formState[2].children = [];
  formState.value.PC.formState[3].children = [];
  formState.value.Mobile.formState[2].children = [];
  formState.value.Mobile.formState[3].children = [];
  ['PC', 'Mobile'].forEach((type_item: string) => {
    let comSelectCfgTmp = cloneDeep(comSelectCfg);
    comSelectCfgTmp.rule.required = false;
    Lists = [];
    data[type_item == 'PC' ? 'pcTplSetup' : 'mobileTplSetup'].channelModels.forEach((item: dataSourceType) => {
      let obj = Object.assign(comSelectCfgTmp, { label: item.modelName, param: item.modelId, value: item.homeTpl || '' });
      formState.value[type_item][item.modelId] = item.tplPath || '';
      Lists.push(cloneDeep(obj));
    })
    formState.value[type_item].formState[2].children = cloneDeep(Lists);
    Lists = [];
    data[type_item == 'PC' ? 'pcTplSetup' : 'mobileTplSetup'].contentModels.forEach((item: dataSourceType) => {
      let obj = Object.assign(comSelectCfgTmp, { label: item.modelName, param: item.modelId, value: item.homeTpl || '' });
      formState.value[type_item][item.modelId] = item.tplPath || '';
      Lists.push(cloneDeep(obj));
    })
    formState.value[type_item].formState[3].children = cloneDeep(Lists);
    onChangeSelect(0, 0, {})
  });

  getAllOptions()// 获取回填的模板方案下的options
  console.log(formState.value, 'formState.value')
}
//onMounted
onMounted(() => {
  getSiteDetail_tempeleteInfo();
})
// defineExpose
defineExpose({ getbaseForm, saveTplData });
</script>
<style lang="less" scoped>
.tempeleteFrom {
  height: 100%;
  overflow: hidden;

  .tab_card {
    margin-top: 24px;
  }

  .ant-tabs.ant-tabs-top {
    height: auto;
  }

  .tab-pane {
    padding-top: 24px;
    display: flex;

    span {
      width: calc(50% - 32px);
    }

    span:nth-of-type(1) {
      margin-right: 40px;
    }

  }

  .scrollContent {
    height: calc(100% - 80px);
    overflow-y: auto;
    padding-right: 24px;

    .scrollContent_form {
      display: flex;

      .form_item {
        width: calc(50% - 20px);
      }

      .form_item:nth-of-type(1) {
        margin-right: 40px;
      }

      ::v-deep(.ant-form-item .ant-select) {
        width: 100%;
        max-width: 400px;
      }
    }
  }



}
</style>
<style lang="less">
.tempeleteFrom {
  .globalContentModels {
    margin-left: 32px;

    .ant-checkbox-group {
      display: flex;
      flex-wrap: wrap;

      .ant-checkbox-group-item {
        margin-right: 8px;
        width: 16%;
        margin-bottom: 12px;
      }
    }
  }

}
</style>
